package com.example.x6.configurationmaintenance.Utils;

import android.content.Context;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class CopyFile {
    private static final String SEPARATOR = File.separator;

    public boolean copyFile(String sourcePath, String aimPath) {
        if (!new File(sourcePath).isFile()) {
            return false;
        }
        try {
            readInputStream(aimPath, new FileInputStream(sourcePath));
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean copyFileFromRaw(Context context, int id, String fileName, String storagePath) {
        InputStream inputStream = context.getResources().openRawResource(id);
        File file = new File(storagePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        return readInputStream(storagePath + SEPARATOR + fileName, inputStream);
    }

    private boolean readInputStream(String storagePath, InputStream inputStream) {
        File file = new File(storagePath);
        if (file.exists()) {
            return true;
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            byte[] buffer = new byte[inputStream.available()];
            while (true) {
                int lenght = inputStream.read(buffer);
                if (lenght != -1) {
                    fileOutputStream.write(buffer, 0, lenght);
                } else {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    inputStream.close();
                    return true;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e2) {
            e2.printStackTrace();
            return false;
        }
    }
}
